package com.jyou.stock;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;


public class Price {
	private static ByteArrayOutputStream getResponse(String url, boolean isPost, int timeoutInMS)
			throws Exception {

		String cookie = null;
		HttpURLConnection conn = null;
		InputStream inputStream = null;
		DataOutputStream out = null;
		
		try {
			URL uUrl = null;
			if (isPost) {
				uUrl = new URL(url);
				conn = (HttpURLConnection) uUrl.openConnection();
				conn.setRequestMethod("POST");
			} else {
				uUrl = new URL(url);
				conn = (HttpURLConnection) uUrl.openConnection();
				conn.setRequestMethod("GET");
			}
			conn.setRequestProperty("Proxy-Connection", "Keep-Alive");

			conn.setReadTimeout(timeoutInMS);
			conn.setConnectTimeout(timeoutInMS);
			conn.setDoOutput(true);
			conn.setDoInput(true);

			if (isPost) {
				out = new DataOutputStream(conn.getOutputStream());
				out.flush();
			}

			inputStream = conn.getInputStream();

			byte[] bytes = new byte[1024];
			int len = 0;
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			while ((len = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, len);
			}
			
			return outputStream;
		} catch (SocketTimeoutException e) {
			
		} catch (Exception e) {
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return null;
	}
	
	public static String getResult(String url){
		String result = "";
		try {
			ByteArrayOutputStream baos = getResponse(url, false, 50000);
			result = baos.toString("UTF-8");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	public static JSONObject getResultByTicker(String ticker) throws DocumentException{
		JSONObject result = new JSONObject();
		Date date = Calendar.getInstance().getTime();
		result.put("date", date.toString());
		result.put("ticker", ticker);
		String url = "http://www.google.com/finance?q=" + ticker;
		String str = getResult(url);
		str = str.replaceAll("<script(?:[^<]++|<(?!/script>))*+</script>", "");
		str = str.replaceAll("<style(?:[^<]++|<(?!/style>))*+</style>", ""); 
		str = str.replaceAll("<head(?:[^<]++|<(?!/head>))*+</head>", "");
		str = str.replaceAll("<html", "<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		int start = str.indexOf("<div id=price-panel class=\"id-price-panel goog-inline-block\">");
		int end = str.indexOf("<div class=\"snap-panel-and-plusone\">");
		String priceStr = str.substring(start, end);
		end = priceStr.indexOf("<span class=nwp>");
		priceStr = priceStr.substring(0, end);
		priceStr = priceStr.replace("<div id=price-panel class=\"id-price-panel goog-inline-block\">", "");
		end = priceStr.lastIndexOf("<div>");
		priceStr = priceStr.substring(0, end);
		Document doc = DocumentHelper.parseText(priceStr);
		Element priceEl = (Element) doc.selectSingleNode("div/span").selectSingleNode("span");
		String price = priceEl.getText();
		List<Element> temEls = doc.selectNodes("div/div/span/span");
		
		JSONArray ja = new JSONArray();
		ja.add(price);
		for(Element el : temEls){
			ja.add(el.getText());
		}
		result.put("info", ja);
		start = str.indexOf("data-snapfield=\"range\">");
		end = str.indexOf("data-snapfield=\"range_52week\">");
		String rangeStr = str.substring(start, end);
		start = rangeStr.indexOf("<td class=\"val\">");
		end = rangeStr.lastIndexOf("</td>");
		rangeStr = rangeStr.substring(start, end);
		rangeStr = rangeStr.replaceAll("<td class=\"val\">", "");
		result.put("range", rangeStr);
		return result;
	}
	
	
	private static boolean isTradeDay(){
		boolean result = false;
		Calendar calendar = Calendar.getInstance();
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);
		int second = calendar.get(Calendar.SECOND);
		int week = calendar.get(Calendar.DAY_OF_WEEK);
		if(week >= 2 && week <= 6){
			int temp = hour * 60 * 60 + minute * 60 + second;
			int amStart = 9 * 60 * 60 + 30 * 60;
			int amEnd = 11 * 60 * 60 + 30 * 60;
			int pmStart = 13 * 60 * 60;
			int pmEnd = 15 * 60 * 60 + 30 * 60;
			result = (temp >= amStart && temp <= amEnd) || (temp >= pmStart && temp <= pmEnd);
		}
		return result;
	}
	
	/**
	 * @param args
	 * @throws DocumentException 
	 * @throws InterruptedException 
	 */
	public static void start() throws Exception{
		//http://www.google.com/finance?q=SHA:000001
		//http://www.google.com/finance?q=SHE:000004
		//zgbc : 601299
		//zgnc : 601766
		String[] tickers = {"SHA:000001", "SHA:601299", "SHA:601766", "SHA:600036", "SHA:600115"};
		for(int i = 0; i < tickers.length; i++){
			getResultByTicker(tickers[i]);
		}
	}
	
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		JSONObject res = getResultByTicker("SHA:000001");
		System.out.println(res.toString());
	}

}
